<template>
    <!-- 头部 -->
    <van-nav-bar title="地址列表" left-arrow @click-left="$router.back()">
        <template #right>
            <van-icon name="ellipsis" />
        </template>
    </van-nav-bar>
    <!--地址列表 -->
    <van-address-list v-model="address.chosenAddressId" :list="address.list" default-tag-text="默认" @add="onAdd"
        @edit="onEdit" @click-item="enterOrder" />
</template>
<script setup>
import { reactive, onMounted, ref } from 'vue'
import { addressList } from "@/api/index.js"
import { useRouter, useRoute } from "vue-router"
import { showConfirmDialog } from 'vant';
let route = useRoute()
let router = useRouter()
let address = reactive({
    list: [],
    chosenAddressId: ''
})
let edit = ref(true)
onMounted(() => {
    getData().then(() => {
        let res = address.list.filter(item => item.isDefault == true)
        address.chosenAddressId = res[0].id
    })
})
// 根据地区 获取地址
let getAreaCode = (area) => {
    area = area.replace(/区|县/, '')
    for (let k in areaList.county_list) {
        if (areaList.county_list[k].includes(area)) {
            return k
        }
    }
}
async function getData() {
    await addressList().then(res => {
        if (res.resultCode == 200) {
            address.list = res.data.map(item => {
                return {
                    id: item.addressId,
                    name: item.userName,
                    tel: item.userPhone,
                    address:
                        item.provinceName +
                        item.cityName +
                        item.regionName +
                        item.detailAddress,
                    isDefault: item.defaultFlag
                }
            })

        }
    })
}
// 添加地址
let onAdd = () => {
    router.push('/addressAdd')
}
// 编辑地址
let onEdit = (item) => {
    console.log(item.id);
    edit.value = false
    router.push('/addressAdd?addressId=' + item.id)
}
// 点击进入创建订单
let enterOrder = (item) => {
    if (!edit) {
        return
    }
    showConfirmDialog({
        title: '确认地址',
        message:
            '是否选择此地址',
    }).then(() => {
        router.push({
            path: "/create-order",
            query: { addressId: item.id }
        })
    })
}
</script>